import {
  _decorator,
  Component,
  Node,
  CCFloat,
  CCInteger,
  director,
  AudioClip,
  AudioSource,
} from "cc";
const { ccclass, property } = _decorator;

@ccclass("Audio")
export class Audio extends Component {
  @property(CCFloat)
  bgmVolume = 1.0;
  @property(CCFloat)
  sfxVolume = 1.0;
  @property(CCInteger)
  bgmAudioID = -1;
  @property(AudioSource)
  bgmSource = null as AudioSource;
  @property(AudioSource)
  sfxSource = null as AudioSource;
  constructor() {
    super();
    let audioMgr = new Node();
    audioMgr.name = "__audioMgr__";
    //@en add to the scene.
    //@zh 添加节点到场景
    director.getScene().addChild(audioMgr);
    //@en make it as a persistent node, so it won't be destroied when scene change.
    //@zh 标记为常驻节点，这样场景切换的时候就不会被销毁了
    director.addPersistRootNode(audioMgr);
    //@en add AudioSource componrnt to play audios.
    //@zh 添加 AudioSource 组件，用于播放音频。
    this.bgmSource = audioMgr.addComponent(AudioSource);

    let sfxAudioMgr = new Node();
    sfxAudioMgr.name = "__audioMgr__";
    //@en add to the scene.
    //@zh 添加节点到场景
    director.getScene().addChild(sfxAudioMgr);
    //@en make it as a persistent node, so it won't be destroied when scene change.
    //@zh 标记为常驻节点，这样场景切换的时候就不会被销毁了
    director.addPersistRootNode(sfxAudioMgr);
    //@en add AudioSource componrnt to play audios.
    //@zh 添加 AudioSource 组件，用于播放音频。
    this.sfxSource = sfxAudioMgr.addComponent(AudioSource);
    this.bgmSource.loop = true;
  }
  start() {
    let t = cc.sys.localStorage.getItem("bgmVolume");
    if (t != null) {
      this.bgmVolume = parseFloat(t);
    }

    t = cc.sys.localStorage.getItem("sfxVolume");
    if (t != null) {
      this.sfxVolume = parseFloat(t);
    }

    cc.game.on(cc.game.EVENT_HIDE, () => {
      this.bgmSource && this.bgmSource.pause();
      // this.sfxSource.pause();
    });
    cc.game.on(cc.game.EVENT_SHOW, () => {
      this.bgmSource && this.bgmSource.play();
      // this.sfxSource.play();
    });
  }
  getUrl(url = "", cb: (a: AudioClip) => any) {
    url = url.substring(0, url.lastIndexOf("."));
    return cc.resources.load(
      "sounds/" + url,
      AudioClip,
      (err, clip: AudioClip) => {
        if (!err && typeof cb === "function") {
          cb(clip);
        }
      }
    );
  }
  playBGM(url = "") {
    let self = this;
    return self.getUrl(url, (audio: AudioClip) => {
      if (self.bgmSource && self.bgmSource.clip) {
        self.bgmSource.pause();
      }
      console.log(self.bgmSource, "?self.bgmSource", self);
      self.bgmSource.clip = audio;

      // audio, true, self.bgmVolume
      // self.bgmAudioID = ;
      self.bgmSource.play();
    });
  }
  playSFX(url = "") {
    return this.getUrl(url, (audio) => {
      if (this.sfxVolume > 0) {
        this.sfxSource.clip = audio;
        this.sfxSource.play();
        // cc.audioEngine.play(audio, false, this.sfxVolume);
      }
    });
  }
  update(deltaTime: number) {}
}
